<template>
  <el-main class="add-main">
    <div class="upload-container">
      <!-- 文件上传区域 -->
      <el-upload class="npy-uploader" drag :auto-upload="true" :http-request="uploadFile" :show-file-list="false"
        accept=".npy">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          拖拽 .npy 文件到此处或<em>点击选择</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          支持单张图像 (H,W,C) 或批量图像 (B,H,W,C)
        </div>
      </el-upload>

      <!-- 结果显示区域 -->
      <div class="result-container" v-if="results.length > 0">
        <h3>预测结果</h3>
        <div class="result-card" v-for="(result, index) in results" :key="index">
          <div class="prediction">
            诊断: <span :class="{ 'cn': result.label === 'CN', 'ad': result.label === 'AD' }">
              {{ result.label === 'CN' ? '认知正常(CN)' : '阿尔茨海默病(AD)' }}
            </span>
          </div>
          <div class="confidence">
            置信度:
            <el-progress :text-inside="true" :stroke-width="20" :percentage="Math.round(result.confidence * 100)"
              status="success" :color="customColors" />
          </div>
          <div class="probabilities">
            <div>类别概率分布：</div>
            <div>AD: {{ (result.probabilities['0'] * 100).toFixed(1) }}%</div>
            <div>CN: {{ (result.probabilities['1'] * 100).toFixed(1) }}%</div>
          </div>

          <!-- 修正后的就医建议模块 -->
          <div class="advice-section">
            <h4><i class="el-icon-first-aid-kit"></i> AI就医建议</h4>
            <div class="advice-content" v-html="renderMarkdown(result.advice)" />
            <el-button type="primary" size="small" @click="copyAdvice(result.advice)" class="copy-btn">
              复制建议
            </el-button>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div class="loading-container" v-if="isLoading">
        <el-progress type="circle" :percentage="100" status="success" :indeterminate="true" />
        <p>模型预测中...</p>
      </div>

      <!-- 错误提示 -->
      <div class="error-container" v-if="errorMessage">
        <el-alert :title="errorMessage" type="error" effect="dark" show-icon :closable="true"
          @close="errorMessage = ''" />
      </div>
    </div>
  </el-main>
</template>

<script setup>
import { ref } from 'vue';
import { ElNotification, ElMessage } from 'element-plus';
import { marked } from 'marked'; // 导入marked库
import { useModelStore } from '@/stores/model';
import { classifyNpy } from '@/api/add'

const props = defineProps(['modelName', 'modelIntro', 'servedModelName']);
const modelStore = useModelStore();
// 初始化响应式变量
const results = ref([]);
const isLoading = ref(false);
const errorMessage = ref('');

// 进度条自定义颜色
const customColors = [
  { color: '#909399', percentage: 20 },
  { color: '#e6a23c', percentage: 50 },
  { color: '#67c23a', percentage: 80 },
  { color: '#5cb87a', percentage: 100 }
];

// Markdown渲染函数
const renderMarkdown = (text) => {
  if (!text) return '';
  return marked(text);
};

// 上传文件并获取预测结果
const uploadFile = async (fileOptions) => {
  const file = fileOptions.file;

  isLoading.value = true;
  errorMessage.value = '';
  results.value = [];

  // 检查文件类型
  if (!file.name.toLowerCase().endsWith('.npy')) {
    errorMessage.value = '请上传 .npy 格式的文件';
    isLoading.value = false;
    return;
  }

  try {
    // 通过统一 API 封装进行分类
    const res = await classifyNpy({ file })
    const data = res

    // 处理返回结果
    if (data.error) {
      errorMessage.value = data.error;
    } else {
      // 确保结果始终是数组格式
      results.value = Array.isArray(data) ? data : [data];

      // 显示成功通知
      ElNotification({
        title: '预测成功',
        message: `完成${results.value.length}张图像的诊断`,
        type: 'success',
        duration: 3000
      });
    }
  } catch (error) {
    console.error('请求出错:', error);
    const status = error?.response?.status;
    const serverMsg = typeof error?.response?.data === 'string' ? error.response.data : (error?.response?.data?.error || '');
    errorMessage.value = `处理失败: ${status ? `HTTP ${status} ` : ''}${serverMsg || (error.message || '未知错误')}`;
  } finally {
    isLoading.value = false;
  }
};

// 复制建议到剪贴板
const copyAdvice = (text) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('建议已复制到剪贴板');
  }).catch(err => {
    console.error('复制失败:', err);
    ElMessage.error('复制失败，请手动选择文本复制');
  });
};
</script>

<style lang="scss" scoped>
.add-main {
  height: 100%;
  display: flex;
  flex-direction: column;

  .upload-container {
    flex: 1;
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .npy-uploader {
      width: 100%;
      max-width: 500px;
      margin-bottom: 30px;
    }

    .result-container {
      width: 100%;
      max-width: 600px;
      border-radius: 8px;
      padding: 20px;

      h3 {
        margin-bottom: 15px;
        color: #303133;
        text-align: center;
      }

      .result-card {
        background: white;
        border-radius: 6px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

        .prediction {
          font-size: 18px;
          margin-bottom: 15px;
          font-weight: bold;

          .cn {
            color: #67c23a;
          }

          .ad {
            color: #f56c6c;
          }
        }

        .confidence {
          margin-bottom: 15px;
        }

        .probabilities {
          display: flex;
          gap: 15px;
          margin-bottom: 15px;
          color: #606266;
        }

        .advice-section {
          margin-top: 25px;
          padding: 15px;
          background-color: #f0f9ff;
          border-radius: 8px;
          border-left: 4px solid #409eff;
          position: relative;

          h4 {
            color: #1e90ff;
            margin-bottom: 12px;
            display: flex;
            align-items: center;

            i {
              margin-right: 8px;
            }
          }

          .advice-content {
            max-height: 300px;
            /* 设置最大高度 */
            overflow-y: auto;
            /* 添加垂直滚动条 */
            padding: 10px;
            line-height: 1.7;
            margin-bottom: 15px;
            background: white;
            border-radius: 4px;
          }

          .copy-btn {
            position: absolute;
            right: 15px;
            top: 15px;
          }
        }
      }
    }

    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px 0;

      p {
        margin-top: 15px;
        color: #606266;
      }
    }

    .error-container {
      width: 100%;
      max-width: 600px;
      margin-top: 20px;
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .result-card {
    padding: 15px !important;

    .advice-section {
      padding: 12px !important;

      .copy-btn {
        position: static !important;
        margin-top: 10px;
        width: 100%;
      }
    }
  }
}

/* Markdown内容样式 */
.advice-content {
  :deep(h1, h2, h3, h4, h5, h6) {
    font-weight: bold;
    margin: 10px 0;
  }

  :deep(h1) {
    font-size: 1.5em;
  }

  :deep(h2) {
    font-size: 1.4em;
  }

  :deep(h3) {
    font-size: 1.3em;
  }

  :deep(p) {
    margin: 8px 0;
  }

  :deep(ul, ol) {
    margin: 10px 0;
    padding-left: 20px;
  }

  :deep(li) {
    margin-bottom: 5px;
  }

  :deep(strong) {
    font-weight: bold;
  }
}
</style>